package com.kmxd.ams.app.event.move.command;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kmxd.ams.app.event.AmsEventPublisher;
import com.kmxd.ams.client.arrange.IDocumentSvc;
import com.kmxd.ams.client.arrange.IVolumeSvc;
import com.kmxd.ams.client.event.es.EsUpdateDataEvent;
import com.kmxd.ams.client.event.move.VolumeChangeStatusEvent;
import com.kmxd.ams.core.util.DynamicTableNameUtil;
import com.kmxd.ams.infra.arrange.entity.Document;
import com.kmxd.ams.infra.arrange.entity.Volume;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 移动案卷
 *
 * @author nickbi
 */
@Slf4j
@AllArgsConstructor
@Component
public class VolumeChangeStatusCmd {

  private final IVolumeSvc volumeSvc;
  private final IDocumentSvc documentSvc;
  private AmsEventPublisher amsEventPublisher;

  @Transactional(rollbackFor = Exception.class)
  public void move(VolumeChangeStatusEvent event) {
    if (!event.getIds().isEmpty()) {
      // 修改案卷状态为待整理 20231106修改为批量操作
      LambdaUpdateWrapper<Volume> volUpdateWrapper = Wrappers.lambdaUpdate();
      volUpdateWrapper.in(Volume::getId, event.getIds());
      volUpdateWrapper.set(Volume::getStatus, event.getStatus().getCode());
      DynamicTableNameUtil.setTableName(event.getTableId());
      volumeSvc.update(volUpdateWrapper);

      // 修改文件状态为待整理
      LambdaUpdateWrapper<Document> docUpdateWrapper = Wrappers.lambdaUpdate();
      docUpdateWrapper.in(Document::getVolId, event.getIds());
      docUpdateWrapper.set(Document::getStatus, event.getStatus().getCode());
      DynamicTableNameUtil.setTableName(event.getDocTableId());
      documentSvc.update(docUpdateWrapper);

      amsEventPublisher.publishEvent(
          new EsUpdateDataEvent(event.getIds(), event.getArchTypeId(), event.getTableId()));
    }
  }
}
